package com.example.springboothello.conf;

import com.example.springboothello.entity.ResultVO;
import com.example.springboothello.exception.APIException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestControllerAdvice
public class ExceptionControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVO MethodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        // 从异常对象中拿到ObjectError对象
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        Map map = new HashMap<String,String>();
        if(allErrors != null && allErrors.size()>0){
            for (ObjectError error : allErrors) {
                map.put(error.getObjectName(),error.getDefaultMessage());
            }
        }
        // 然后提取错误提示信息进行返回
        //return map;
        return new ResultVO<>(1001, "参数校验失败", map);
    }
    @ExceptionHandler(APIException.class)
    public ResultVO APIExceptionHandler(APIException e) {
        //return e.getMsg();
        return new ResultVO<>(e.getCode(), "响应失败", e.getMsg());
    }
}
